package com.tencet.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author: Fame
 * @date: 2022-07-18 19:33
 * @description:获取数据库连接
 */
public class JDBCUtils {

    public static DataSource dataSource;
    public static Connection conn;

    static {

        Properties properties = new Properties();
        dataSource = null;
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            conn = dataSource.getConnection();
        } catch  (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }
    /**
     * 返回Connection连接
     * @return
     */
    public static Connection getConnection(){
        try {
            Connection connection = dataSource.getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
            return  null;
    }

    /***
     * @description TODO 返回Connection连接，并且设事务为手动提交
     * @author Yangjx
     * @param
     * @createTime
     * @return
     */

    public static Connection connAndAutoCommit(){
        try {
            conn.setAutoCommit(false);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description TODO 事务的提交
     * @author Yangjx
     * @throws SQLException
     */
    public static void justCommit() throws SQLException {
        System.out.println(conn);
        conn.commit();
        closeConn(conn);
    }

    /**
     * @Description TODO 事务回滚
     * @author Yangjx
     * @throws SQLException
     */
    public static void rollback() throws SQLException {
        getConnection().rollback();
        closeConn(getConnection());
    }

    /**
     * Connection资源关闭
     * @param conn
     */
    public static void closeConn(Connection conn){
        DbUtils.closeQuietly(conn);
    }
}
